/**
 * @author xxx
 * @time 2022-04-19 16PM
 * @description 路由定义
 */

/** 插件注册 */
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/** 引入store实例 */
import store from '../store'

/** 重写push方法 */
const pushPlugin = Router.prototype.push
Router.prototype.push = function (_params) {
    pushPlugin.call(this, _params).catch(e => {
    })
}

/** 路由组件注册 */
const Login = () => import('../pages/login')
const Register = () => import('../pages/login/Register')
const Home = () => import('../pages/home/content')
const Me = () => import('../pages/me')
const Details = () => import('../pages/details')
const Type = () => import('../pages/type')
const Car = () => import('../pages/car')
const Password = () => import('../pages/login/password')
const Video = () => import('../pages/video')


/** 实例化 */
const router = new Router({
    routes: [{
            path: '/',
            redirect: '/login'
        },
        {
            path: '/login',
            component: Login,
            meta: {
                needLogin: false
            }
        },
        {
            path: '/password',
            component: Password,
            meta: {
                needLogin: false
            }
        },
        {
            path: '/register',
            component: Register,
            meta: {
                needLogin: false
            }
        },
        {
            path: '/index',
            component: Home,
            children: [{
                    redirect: 'home',
                    path: '',
                },

                {
                    path: 'home',
                    component: () => import(`../pages/home`)
                },
                {
                    path: 'type',
                    component: Type
                },
                {
                    path: 'cart',
                    component: Car
                },
                {
                    path: 'me',
                    component: Me
                },
                {
                    path: 'video',
                    component: Video
                },
            ]
        }, 
        {
            path: '/details',
            component: Details
        },

    ]
})

/** 实现路由权限全局拦截 */
const roleCallback = function (to, from, next) {
    /* 权限拦截 */
    let needLogin = to.meta.needLogin
    if (needLogin === false) {
        next()
        return
    }

    /* 从vuex中获取token数据 */
    let flag = store.getters['common/token']
    if (!!flag) {
        next()
        return
    }
    next('/login')
}
router.beforeEach(roleCallback)

/** 导出路由实例对象 */
export default router